import info from '../js/info'

const tool = {
	// serviceUrl: 'http://192.168.1.144:8080',
	// websocketUrl: "ws://192.168.1.144:8080", //websockey；链接

  serviceUrl:'https://www.ivvajob.com',
  websocketUrl:'wss://www.ivvajob.com',
	/*获取当前UR*/
	getPageUrl() {
		var pages = getCurrentPages() //获取加载的页面

		var currentPage = pages[pages.length - 1] //获取当前页面的对象

		let urlData = this.encodeSearchParams(currentPage.options)

		return currentPage.route + (urlData ? `?${urlData}` : '') //当前页面urlL
	},

	//验证邮件格式
	verifyEmail(value) {
		var result = new RegExp("^([a-z0-9A-Z]+[-|_\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
		if (!value) {
			return {
				flag: false,
				message: '邮箱不能为空'
			};
		} else if (result.test(value)) {
			return {
				flag: true,
				message: '验证成功'
			};
		} else {
			return {
				flag: false,
				message: '邮箱格式不正确'
			};
		}
	},
	//验证手机号
	verifyMobile(value) {
		if (!value) {
			return {
				flag: false,
				message: '手机号不能为空'
			};
		} else if (/^[1][34578]\d{9}$/.test(value)) {
			return {
				flag: true,
				message: '验证成功'
			};
		} else {
			return {
				flag: false,
				message: '手机号格式不正确'
			};
		}

	},

	//验证网址格式
	verifyWebsite(value) {
		var regExp = /^((https?|http|ftp|news):\/\/)+([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/;
		if (regExp.test(value)) {
			return {
				flag: true,
				message: '验证成功'
			};
		} else {
			return {
				flag: false,
				message: '网址格式不正确'
			};
		}
	},

	//6位验证手机验证码
	verifyMobileCode(value) {
		if (value.length !== 6) {
			return {
				flag: false,
				message: '请填写6位数字的手机验证码'
			};
		} else if (!/[0-9]{6}/.test(value)) {
			return {
				flag: false,
				message: '验证码不正确'
			};
		} else {
			return {
				flag: true,
				message: '验证成功'
			};
		}
	},

	//验证密码格式
	verifyPwd(value) {
		if (value.length < 6 || value.length > 16) {
			return {
				flag: false,
				message: '请填写6-16位密码'
			};
		} else if (!/^[0-9A-Za-z_]{6,16}$/.test(value)) {
			return {
				flag: false,
				message: '密码只能是字母、数字、下划线'
			};
		} else {
			return {
				flag: true,
				message: '验证成功'
			};
		}
	},

	//验证两个字符是否一致
	verifySame(value1, value2) {
		if (value1 == value2) {
			return {
				flag: true,
				message: '验证成功'
			};
		} else {
			return {
				flag: false,
				message: '两次输入不一致'
			};
		}
	},

	//验证图形验证码
	verifyImgCode(value) {
		if (!value) {
			return {
				flag: false,
				message: '验证码不能为空'
			};
		} else if (!/^[0-9A-Za-z_]{4}$/.test(value)) {
			return {
				flag: false,
				message: '验证码只能是数字或字母'
			};
		} else {
			return {
				flag: true,
				message: '验证成功'
			};
		}
	},
  /*获取基本数组*/
  getMinArray(array){
    let minArray = []
    for(let i in array){
      minArray.push({
        index:i,
        id:array[i].id,
        value:array[i].value,
      })
    }
    return minArray
  },
	/* 倒计时*/
	countTime(eleId, sec, initFn, callbackFn) {
		var time = sec;
		var obj = document.getElementById(eleId);
		obj.classList.add('fd-btn-disabled');
		document.getElementById(eleId).innerHTML = sec + '秒后可重试';
		initFn();

		var handle = setInterval(function () {
			time--;
			obj.innerHTML = time + '秒后可重试';
			if (time < 1) {
				clearInterval(handle);
				obj.innerHTML = '获取验证码';
				obj.classList.remove('fd-btn-disabled');
				if (typeof callbackFn == "function") {
					callbackFn();
				}
			}
		}, 1000);
	},

	/*查询当前值是否在数组中*/
	findInArr(arr, value) {
		for (var index in arr) {
			if (arr[index] == value) {
				return true;
				break;
			}
		}
		return false;
	},

	/*查询当前值在数组中的索引*/
	findIndexInArr(arr, value, name) {
		for (var index in arr) {
		  if(name){
        if (arr[index][name] == value) {
          return index;
          break;
        }
      }else{
        if (arr[index] == value) {
          return index;
          break;
        }
      }
		}
		return '';
	},
  /*匹配字段ID*/
  findIdArr(Arr,fieldId,index){
    if(Arr){
      for(let i in Arr){
        if(Arr[i].customFieldId==fieldId){
          return Arr[i][index||'id']
        }
      }
    }
    return ''
  },
	/*删除数组的指定索引元素*/
	removFromArr(arr, index, callbackFn) {
		arr.splice(index, 1); //删除指定位置的元素
		if (typeof callbackFn == "function") {
			callbackFn();
		}
	},

	/*是否按下键盘的数字键*/
	isNumKey() {
		var keyCode = event.keyCode;
		if ((keyCode >= 48 && keyCode <= 57)) {
			event.returnValue = true;
		} else {
			event.returnValue = false;
		}
	},

	//日期转换格式转换----函数
	formatDate(date, format) {
		if (typeof date == "string") date = new Date(date);
		var o = {
			"M+": date.getMonth() + 1, //month
			"d+": date.getDate(), //day
			"h+": date.getHours(), //hour
			"m+": date.getMinutes(), //minute
			"s+": date.getSeconds(), //second
			"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
			"S": date.getMilliseconds() //millisecond
		}
		if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(format))
				format = format.replace(RegExp.$1,
					RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		return format;
	},

	//时间范围判断
	dateJudge(start, end) {
		//start = 00:00 时间格式
		//end = 00:00 时间格式
		if (!start || !end) {
			return {
				flag: false,
				message: '请传入开始及结束时间'
			};
		} else {
			start = start.split(':');
			end = end.split(':');
			const date = new Date();
			let h = date.getHours(),
				m = date.getMinutes()
			if (start[0] < h || start[0] == h && start[1] <= m) {
				if (end[0] > h || end[0] == h && end[1] >= m) {
					return {
						flag: true,
						message: '时间范围正确'
					};
				} else {
					return {
						flag: false,
						message: '当前时间大于范围'
					};
				}
			} else {
				return {
					flag: false,
					message: '当前时间小于范围'
				};
			}
		}
	},

	/*get请求字符串拼接*/
	encodeSearchParams(obj) {
		const params = []

		Object.keys(obj).forEach((key) => {
			let value = obj[key]
			// 如果值为undefined我们将其置空
			if (typeof value === 'undefined') {
				value = ''
			}
			// 对于需要编码的文本（比如说中文）我们要进行编码
			params.push([key, encodeURIComponent(value)].join('='))
		})

		return params.join('&')
	},

	//ajax请求
	ajax(param) {
		var config = {
			url: param.url, //请求url
			data: param.data || {}, //请求参数
			type: param.type || 'POST', //请求方式，默认为post
			loading: param.loading, //是否需要loading动画，默认为true
			success: param.success, //请求成功回调函数
			error: param.error //请求失败回调函数
		}
		if (!config.url) {
			alert('url required');
			return
		}
		if (config.loading === undefined) config.loading = true;
		if (config.loading) tool.loading(true);
		let objData = []
		for (var i in config.data) {
			if (config.data[i] === '' || config.data[i] === null || config.data[i] === undefined) {
				delete config.data[i];
				continue;
			}
		}
		if (!config.data.rd_session) {
		  // console.log(wx.getStorageSync('rd_session'))
			config.data.rd_session = wx.getStorageSync('rd_session') || ''
		}
		// config.data.requestCityCode = wx.getStorageSync('requestCityCode') || '';
		// config.data.requestLatitude = wx.getStorageSync('requestLatitude') || '';
		wx.request({
			url: config.url,
			data: config.data,
			method: config.type,
			header: {
				'content-type': config.type.toUpperCase() == 'POST' ? 'application/x-www-form-urlencoded' : 'application/json',
			},
			success(res) {
				if (res.data.code == 444) {
          tool.loading(false);
          wx.removeStorageSync('userId');
          tool.showToastText(res.data.message);
          wx.redirectTo({
            url: '/pages/index/main'
          })
					//					window.location.href = "/login/login?backUrl=" + encodeURIComponent(window.location.href);
					config.success(res.data);
				} else if (res.data.code == 304) {
					const app = getApp();
					let loginSatus = app.data.loginStatus;
					if (loginSatus) {
						app.data.loginStatus = false
					}
					wx.clearStorageSync();
					config.success(res.data);
					if (config.loading) tool.loading(false);
				} else if (typeof config.success == "function") {
					config.success(res.data);
					if (config.loading) tool.loading(false);
				};
			},
			fail(error) {
				if (config.loading) tool.loading(false);
				if (typeof config.error == "function") {
					config.error(error);
				}
				console.error(error + ' on ' + config.url);
			}
		})
	},
	/*控制台打印*/
	console(data) {
		console.clear();
		if (console.table) {
			var consoleArr = [];
			for (var key in data) {
				var value = data[key];
				if (typeof value !== 'string') {
					value = JSON.stringify(data[key]);
				}
				consoleArr.push([key, value])
			}
			console.table(consoleArr);
		} else {
			console.log(data);
		}
	},
	/*模拟异步请求*/
	simulation(data, success) {
		this.console(data)
		setTimeout(success({
			success: true,
			message: '操作成功'
		}), 50)
	},
	/*加载动画*/
	loading(state) {
		if (!!state) {
			wx.showToast({
				title: "loading",
				icon: 'loading',
				duration: 100000,
        mask:true
			})
		} else {
			wx.hideToast()
		}
	},
	/*打印提示*/
	showToastText(title, type, time) {
		setTimeout(() => {
			wx.showToast({
				title: title,
				icon: type ? "success" : "none",
				duration: time ? time : 4000,
        mask:true
			})
		}, 15)
	},
	/*前端筛选*/
	/*searchListCopy(str, container) {
    var newList = [];
    //新的列表
    var startChar = str.charAt(0);
    //开始字符
    var strLen = str.length;
    //查找符串的长度

		let maxTextLength = 0
    for (var i = 0; i < container.length; i++) {
        var obj = container[i];
        var isMatch = false;
        for (var p in obj) {
  if (typeof (obj[p]) == "function") {
    obj[p]();
  } else {
    var curItem = "";
    if (obj[p] != null) {
      curItem = obj[p];
    }
    for (var j = 0; j < curItem.length; j++) {
      if (curItem.charAt(j) == startChar)
      {
        if (curItem.substring(j).substring(0, strLen) == str)
        {
          isMatch = true;
          break;
        }
      }
    }
  }
        }
        if (isMatch) {
        	if(maxTextLength<obj.value.length){
        		maxTextLength = obj.value.length
        	}
          newList.push(obj);
        }
    }
    if(newList.length>1){
	    newList = newList.sort(
			    function compareFunction(param1, param2) {
					return param1.value.localeCompare(param2.value,"zh");
			    }
			)
	    let list = [];
	    for(let i = 0; i < maxTextLength; i++){
	    	for(let j in newList){
	    		newList[j].value.split('')
	    		if(newList[j].value.substring(i).substring(0, strLen) == str){
	    			list.push(newList[j]);
	    		}
	    	}
	    }
	    newList = list
    }

    return newList;
	},*/
	/*前端筛选*/
	searchList(str, container) {
		var newList = [];
		//新的列表
		var startChar = str.charAt(0);
		//开始字符
		var strLen = str.length;
		//查找符串的长度

		let maxTextLength = 0

		for (let i in container) {
			var obj = container[i];
			var isMatch = false;
			for (var p in obj) {
				if (typeof (obj[p]) == "function") {
					obj[p]();
				} else {
					var curItem = "";
					if (obj[p] != null) {
						curItem = obj[p].value;
					}
					for (let j = 0; j < curItem.length; j++) {
						if (curItem.charAt(j) == startChar) {
							if (curItem.substring(j).substring(0, strLen) == str) {
								if (maxTextLength < curItem.length) {
									maxTextLength = curItem.length
								}
								newList.push(obj[p]);
								break;
							}
						}
					}
				}
			}
		}
		if (newList.length > 1) {
			newList = newList.sort(
				function compareFunction(param1, param2) {
					return param1.value.localeCompare(param2.value, "zh");
				}
			)
			let list = [];
			for (let i = 0; i < maxTextLength; i++) {
				for (let j in newList) {
					newList[j].value.split('')
					if (newList[j].value.substring(i).substring(0, strLen) == str) {
						list.push(newList[j]);
					}
				}
			}
			newList = list
		}
		return newList;
	},
};
export default tool;
